import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/http_server/dictionaries.dart';
import 'package:loxen/api/http_server/file_change_delete_add_select.dart';
import 'package:loxen/dialog/dialog_utils.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/master/file_list_bean.dart';
import 'package:loxen/mode/master/file_loxen.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';

class MineStudyFileWidget extends StatelessWidget
    with FileChangeDeleteAddSelectMixin {
  const MineStudyFileWidget({Key key}) : super(key: key);

  // 编辑
  void changeName(
      BuildContext contextMain, _ItemViewModel viewModel, FileLoxen file) {
    showDialog<String>(
      context: contextMain,
      builder: (context) {
        return DialogUtil.getChangeFileNameDialog(context, file,
            showPrivate: false, onChange: (select, text) {
          Stream<int> data;
          if (text.trim() != file.name) {
            data =
                fileChangeName(file.id.toString(), name: text, isHide: select);
          } else {
            data = fileChangeName(file.id.toString(), isHide: select);
          }
          data.listen((event) {
            if (event == 200) {
              file.name = text;
              file.isHide = select;
              viewModel.notifier();
            } else {
              Toast.show("修改失败", contextMain);
            }
          }, onError: (error, stack) {
            Toast.show("网络异常", contextMain);
            print(error);
            print(stack);
          });
        });
      },
    );
  }

  Widget _tabTitle(BuildContext context, String str, FileType type) {
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(Routes.master_file_list, arguments: {
          'type': type,
          'isMe': true,
        }).then((value) => context.read<_ViewHolder>().loadData());
      },
      child: Container(
        margin: EdgeInsets.only(left: 37.w, right: 37.w, top: 40.h),
        height: 45.h,
        decoration: BoxDecoration(
            border: Border(
                left: BorderSide(
                    color: Theme.of(context).primaryColor, width: 5.w))),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 20.w),
                child: Container(
                  margin: EdgeInsets.only(bottom: 0.h),
                  child: Text(
                    str,
                    style: TextStyle(
                        fontSize: 31.sp,
                        fontWeight: FontWeight.bold,
                        color: Theme.of(context).textTheme.subtitle2.color),
                  ),
                  alignment: Alignment.topLeft,
                ),
              ),
            ),
            Text(
              StringResources.cha_kan_geng_duo,
              style: TextStyle(
                  fontSize: 24.sp,
                  color: Theme.of(context).primaryTextTheme.subtitle1.color),
            ),
            Padding(
              padding: EdgeInsets.only(left: 8.w),
              child: Icon(
                Icons.navigate_next,
                color: Theme.of(context).primaryTextTheme.subtitle1.color,
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _files(BuildContext context, List<FileLoxen> files, String type,
      FileType fileType) {
    List<Widget> list = files.map((entity) {
      var data = _ItemViewModel(entity);
      return ChangeNotifierProvider.value(
        value: data,
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            GestureDetector(
              onLongPress: () {
                if (entity.canEdit == 1) changeName(context, data, entity);
              },
              onTap: () {
                Navigator.of(context).pushNamed(Routes.mineStudyFolder,
                    arguments: [
                      type,
                      fileType == FileType.KNOWLEDGE ? 'knowledge' : 'case',
                      entity.id
                    ]).then((value) => context.read<_ViewHolder>().loadData());
              },
              child: Stack(
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    child: ClipRRect(
                        borderRadius: BorderRadius.circular(15.w),
                        child: entity.cover != null && entity.cover != ''
                            ? CachedNetworkImage(
                                imageUrl:  ImageUrlUtil.getClean(entity.cover),
                                placeholder: (_, __) => Constants.loadingIcon(),
                                fit: BoxFit.cover,
                              )
                            : Center(
                                child: Image.asset(
                                  'images/default_folder.png',
                                  width: 57.w,
                                  height: 49.w,
                                ),
                              )),
                    decoration: BoxDecoration(
                        color: Color(0xFF0CB7D9),
                        borderRadius: BorderRadius.all(Radius.circular(15.w))),
                  ),
//                  Builder(builder: (context) {
//                    bool select = context.select<_ItemViewModel, bool>(
//                        (value) => entity.is_hide);
//                    return select
//                        ? AbsorbPointer(
//                            child: Container(
//                              width: double.infinity,
//                              height: double.infinity,
//                              decoration: BoxDecoration(
//                                color: Colors.white.withAlpha(76),
//                                borderRadius: BorderRadius.circular(15.w),
//                              ),
//                              child: Center(
//                                child: Image.asset(
//                                  'images/icon_privacy.png',
//                                  width: 58.w,
//                                  height: 58.w,
//                                ),
//                              ),
//                            ),
//                          )
//                        : Constants.empty;
//                  }),
                ],
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                height: 61.h,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Colors.black.withAlpha(76),
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(15.w),
                    bottomRight: Radius.circular(15.w),
                  ),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.only(left: 25.w),
                      width: double.infinity,
                      child: Builder(builder: (context) {
                        String name =
                            context.watch<_ItemViewModel>().entity.name;
                        return Text(
                          name,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 20.sp,
                              color:
                                  Theme.of(context).textTheme.subtitle1.color,
                              fontWeight: FontWeight.w500),
                        );
                      }),
                    ),
                    Builder(builder: (context) {
                      return Constants.empty;
                    }),
                    Container(
                      padding: EdgeInsets.only(left: 25.w),
                      width: double.infinity,
                      child: Builder(builder: (context) {
                        var num = context.select<_ItemViewModel, int>(
                            (value) => value.entity.num);
                        return Text(
                          '$num$type',
                          style:
                              TextStyle(fontSize: 13.sp, color: Colors.white),
                        );
                      }),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    }).toList();
    return Container(
      height: 240.h,
      width: double.infinity,
      child: list != null && list.length > 0
          ? GridView.count(
              crossAxisCount: 1,
              scrollDirection: Axis.horizontal,
              mainAxisSpacing: 20.w,
              childAspectRatio: 1.5,
              children: list,
            )
          : Center(child: Text('暂无公开文件夹')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<_ViewHolder>(
      create: (BuildContext context) {
        var model = _ViewHolder();
        model.loadData();
        return model;
      },
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 95.h),
          child: Container(
            color: Theme.of(context).backgroundColor,
            child: SafeArea(
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      MySubassembly.getBackIcon(context,
                          color: Theme.of(context).textTheme.subtitle2.color),
                      Expanded(
                        child: Center(
                          child: Text(
                            StringResources.wo_de_xue_xi,
                            style: TextStyle(
                                fontSize: 32.sp,
                                fontWeight: FontWeight.w500,
                                color: Theme.of(context)
                                    .textTheme
                                    .subtitle2
                                    .color),
                          ),
                        ),
                      ),
                      MySubassembly.getSearchIcon(null, text: Text('')),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
        body: Selector<_ViewHolder, BaseState>(
            builder: (context, state, __) {
              if (state == BaseState.LOADING) {
                return LoadingWidget();
              }
              if (state == BaseState.EMPTY) {
                return EmptyWidget();
              }
              if (state == BaseState.FAIL) {
                return FailWidget(
                  onClick: () {
                    context.read<_ViewHolder>().loadData();
                  },
                );
              }
              if (state == BaseState.CONTENT) {
                var studys = context.watch<_ViewHolder>().studys;
                var applys = context.watch<_ViewHolder>().applys;
                return Container(
                  decoration: BoxDecoration(
                    border: Border(
                        top: BorderSide(width: 1.h, color: Color(0xFFEBECF1))),
                    color: Theme.of(context).backgroundColor,
                  ),
                  child: ListView(
                    children: <Widget>[
                      _tabTitle(
                          context, StringResources.zhi_shi, FileType.KNOWLEDGE),
                      Padding(
                        padding: EdgeInsets.only(left: 35.w, top: 24.h),
                        child: _files(context, studys, StringResources.zhi_shi,
                            FileType.KNOWLEDGE),
                      ),
                      _tabTitle(
                          context, StringResources.ying_yong, FileType.APPLY),
                      Padding(
                        padding: EdgeInsets.only(left: 35.w, top: 24.h),
                        child: _files(context, applys,
                            StringResources.ying_yong, FileType.APPLY),
                      ),
                    ],
                  ),
                );
              }
              return Constants.empty;
            },
            selector: (_, model) => model.mState),
      ),
    );
  }
}

class _ItemViewModel extends ChangeNotifier {
  final FileLoxen entity;

  _ItemViewModel(this.entity);

  void notifier() {
    notifyListeners();
  }
}

class _ViewHolder extends BaseViewModel with FileChangeDeleteAddSelectMixin {
  List<FileLoxen> studys;
  List<FileLoxen> applys;

  void loadData() {
    if (mState == BaseState.LOADING) return;
    Rx.zip2<FileListBean, FileListBean, int>(studyFiles(), applyFiles(),
        (a, b) {
      if (a.data != null && b.data != null) {
        studys = a.data.results;
        applys = b.data.results;
        return 200;
      } else {
        return 400;
      }
    }).doOnListen(() {
      mState = BaseState.LOADING;
      notifyListeners();
    }).listen((event) {
      if (event == 400) {
        mState = BaseState.EMPTY;
      } else {
        mState = BaseState.CONTENT;
      }
    }, onError: (error, stack) {
      mState = BaseState.FAIL;
      print(error);
      print(stack);
    }, onDone: () => notifyListeners());
  }

  Stream<FileListBean> studyFiles() {
    return fileSelect('4', pageSize: '20');
  }

  Stream<FileListBean> applyFiles() {
    return fileSelect('5', pageSize: '20');
  }
}
